#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : gtmsAutoTestProject 
@File    : overseas_upload_daily_data_server.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/9/27 10:05 
@Describe: 海外平台 营业额日汇总接口业务实现
"""
import random
from Comm.tools.toolsControl import ToolsHandler
from APIs.posApi.order.order_api import OrderApi


class OverseasUploadDailyDataServer:
    def __init__(self, brandCode, environment):
        self.order_api = OrderApi(brandCode, environment)
        self.shop_code = ToolsHandler.get_shopCode(brandCode)
        self.brand_code = brandCode
        self.environment = environment

    def turnover_data_cleaning(self, start_time: str, end_time: str) -> dict:
        """
        营业额数据清洗
        :param start_time: 开始时间
        :param end_time: 结束时间
        :return:
        """
        businessDay = start_time[0:10]  # 截取开始时间: yyyy-mm-dd
        turnover_data = self.order_api.pos_work_detail(start_time, end_time)  # 获取传入时间的数据
        shopName = ToolsHandler.get_json_result(turnover_data, "$..shopName")
        totalOrderCount = ToolsHandler.get_json_result(turnover_data, "$..totalOrderCount")  # 订单数量（包含退货单）
        consumeAmount = ToolsHandler.get_json_result(turnover_data, "$..consumeAmount")  # 营业总额
        mchRealAmtSum = ToolsHandler.get_json_result(turnover_data, "$..mchRealAmtSum")  # 实收总额
        # 判断营业总额和实收总额是否有对应值。有对应值再计算优惠总额
        if consumeAmount is not None and mchRealAmtSum is not None:
            # 计算优惠总额并舍入2位小数
            totalDiscountAmount = round(consumeAmount - mchRealAmtSum, 2)
        else:
            # 当营业总额和实收总额其中一个没有值的情况,优惠金额等于0
            totalDiscountAmount = 0
        # 组装营业额字典数据
        turnover_dict = {
            "brandCode": self.brand_code,
            "businessDay": businessDay,
            "shopCode": self.shop_code,
            "shopName": shopName,
            "totalAmount": consumeAmount,  # 营业总额
            "totalIncomeAmount": mchRealAmtSum,  # 实收总额
            "totalDiscountAmount": totalDiscountAmount,  # 优惠总额
            "orderNum": totalOrderCount  # 订单数量（包含退货单）
        }
        # 循环营业额字典数据,如果其中有值为None,就赋予0
        for key, values in turnover_dict.items():
            if values is None:
                turnover_dict[key] = 0
        return turnover_dict

    def payment_data_cleaning(self, start_time: str, end_time: str) -> dict:
        """
        支付信息数据清洗
        :param start_time: 开始时间
        :param end_time: 结束时间
        :return:
        """
        businessDay = start_time[0:10]  # 截取开始时间: yyyy-mm-dd
        response = self.order_api.pos_work_detail(start_time, end_time)  # 获取传入时间的数据
        # 获取paymentSituation数据,可能存在没有数据的情况,如:传入的时间没有营业
        payment_data = ToolsHandler.get_json_result(response, "$..paymentSituation")
        # 判断paymentSituation数据是否为空数据,如果不为空就进行数据清洗,如果为空就直接返回一个空数据
        if payment_data is not None:
            brandCode = ToolsHandler.get_json_result(response, "$..brandCode")
            shopCode = ToolsHandler.get_json_result(response, "$..shopCode")
            shopName = ToolsHandler.get_json_result(response, "$..shopName")
            totalOrderCount = ToolsHandler.get_json_result(response, "$..totalOrderCount")  # 订单数量
            # 组装支付数据字典
            paymentSituation = {
                "TotalAmount": payment_data["realAmount"],  # 支付方式合计金额
                "PaymentInfoList": []
            }
            # 循环receivePaymentInfoList列表,把所有的支付方式都进行循环取值
            for i in payment_data["receivePaymentInfoList"]:
                currency = random.randint(1, 5)  # 随机取一个币种
                # 通过支付方式名称判断是否为现金支付
                payName = i["payName"]
                if payName == "现金":
                    paymentWay = "01"
                else:
                    paymentWay = "03"
                payment_dict = {
                    "brandCode": brandCode,
                    "paymentMethod": i["payCode"],  # 支付方式编号
                    "paymentName": i["payName"],  # 支付方式名称
                    "paymentWay": paymentWay,  # 支付类型id：01 现金：当地币种、02银行卡：所有银行卡方式、03 线上支付：如applepay等其他当地流行的线上支付工具、04其他：预留
                    "payAmount": i["amount"],  # 支付金额
                    "orderNum": totalOrderCount,  # 订单数量
                    "currency": currency,  # 币种：1 人民币、2美金、3 新币、4澳币、5 林吉特
                    "businessDay": businessDay,  # 营业日期
                    "shopCode": shopCode,
                    "shopName": shopName
                }
                # 将支付方式明细插入支付数据字典
                paymentSituation["PaymentInfoList"].append(payment_dict)
        else:
            paymentSituation = {}
        return paymentSituation


if __name__ == '__main__':
    test = OverseasUploadDailyDataServer("823882", "sit")
    businessType = test.payment_data_cleaning("2022-09-26 00:00:00", "2022-09-26 23:59:59")
    print(businessType)
